﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Diagnostics;

namespace WP7UIKit.Common
{
    public static class VritualzingGridHelper
    {
        /// <summary>
        /// 虚拟化移除不在当前屏幕的元素
        /// </summary>
        /// <param name="virtualGrid">虚拟化的Grid</param>
        /// <param name="offset">偏移量</param>
        public static void VirtualRemove(this Grid virtualGrid, double offset)
        {
            int childCount = virtualGrid.Children.Count;
            if (childCount > 0)
            {
                for (int i = childCount - 1; i >= 0; i--)
                {
                    FrameworkElement element = (FrameworkElement)virtualGrid.Children[i];
                    double y = element.Margin.Top;
                    double virtualY = y - offset;
                    if (virtualY < -800 || virtualY > 1600)
                    {
                        Debug.WriteLine("虚拟化移除--------------->");
                        virtualGrid.Children.Remove(element);
                    }
                }
            }
        }

        public static void Virtualize(this Grid virtualGrid, double offset, List<FrameworkElement> elements)
        {
            for (int i = elements.Count - 1; i >= 0; i--)
            {
                FrameworkElement element = elements[i];
                double y = element.Margin.Top;
                double virtualY = y - offset;
                if (virtualGrid.Children.Contains(element) && (virtualY <-300 || virtualY >800))
                {
                    //virtualGrid.Children.Remove(element);
                }
                if (!virtualGrid.Children.Contains(element) && (virtualY >= -300 && virtualY <= 800))
                {
                    //virtualGrid.Children.Add(element);
                }
            }
        }

        /// <summary>
        /// 虚拟化添加元素
        /// </summary>
        /// <param name="virtualGrid">虚拟化Grid</param>
        /// <param name="elements">整体的元素集合</param>
        public static void VirtualAdd(this Grid virtualGrid,double offset, List<FrameworkElement> elements)
        {
            foreach (FrameworkElement element in elements)
            {
                double y = element.Margin.Top;
                double virtualY = y- offset;
                if (virtualY >= -800 && virtualY <= 1600)
                {
                    Debug.WriteLine("虚拟化增加--------------->");
                    virtualGrid.Children.Add(element);
                }
            }
        }
    }
}
